<script setup>
import { ElMain, ElMessage, ElMessageBox } from 'element-plus';
import { ref } from 'vue';
// 添加新城市
const newCity = ref('')
const cityData = ref();
const edges = ref();
// 起始地
const src = ref('')
// 目的地
const dest = ref('')
// 车票价格
const price = ref(1)
// 时间范围
const timeRange = ref([])
getData()
function getData() {
    const city = localStorage.getItem("CITY_DATA")
    if (!city) {
        cityData.value = [
            { id: "1", label: "北京" },
            { id: "2", label: "天津" },
            { id: "3", label: "上海" },
            { id: "4", label: "郑州" },
            { id: "5", label: "南昌" },
            { id: "6", label: "广州" },
            { id: "7", label: "株洲" },
            { id: "8", label: "贵阳" },
            { id: "9", label: "重庆" },
            { id: "10", label: "兰州" },
            { id: "11", label: "西宁" },
            { id: "12", label: "成都" },
            { id: "13", label: "昆明" },
            { id: "14", label: "西安" },
            { id: "15", label: "武汉" },
            { id: "16", label: "长沙" },
        ]
        localStorage.setItem("CITY_DATA",JSON.stringify(cityData.value))
    } else {
        cityData.value = JSON.parse(city)
    }
    const edge = localStorage.getItem("EDGE_DATA")
    if (!edge) {
        edges.value = [
            // 北京相关连接，构建多种成本、时间、中转情况的路径起点
            { from: "1", to: "2", cost: 100, time: 20, departureTime: "08:00" },
            { from: "1", to: "3", cost: 1770, time: 50, departureTime: "09:00" },
            { from: "1", to: "4", cost: 50, time: 60, departureTime: "15:00" },
            { from: "1", to: "14", cost: 40, time: 60, departureTime: "08:30" },
            { from: "1", to: "15", cost: 20, time: 90, departureTime: "09:30" },

            // 天津相关连接，延伸路径
            { from: "2", to: "3", cost: 15, time: 25, departureTime: "08:00" },
            { from: "2", to: "4", cost: 15, time: 25, departureTime: "10:00" },
            { from: "2", to: "5", cost: 30, time: 10, departureTime: "11:00" },
            { from: "2", to: "3", cost: 40, time: 60, departureTime: "17:00" },

            // 上海相关连接，拓展路径并构建不同成本、时间组合
            { from: "3", to: "2", cost: 20, time: 30, departureTime: "12:00" },
            { from: "3", to: "4", cost: 20, time: 30, departureTime: "12:00" },
            { from: "3", to: "5", cost: 25, time: 35, departureTime: "13:00" },
            { from: "3", to: "6", cost: 40, time: 40, departureTime: "18:00" },

            // 郑州相关连接，继续串联
            { from: "4", to: "5", cost: 5, time: 10, departureTime: "14:00" },
            { from: "4", to: "14", cost: 30, time: 50, departureTime: "15:00" },

            // 南昌相关连接
            { from: "5", to: "6", cost: 30, time: 40, departureTime: "18:00" },
            { from: "5", to: "15", cost: 25, time: 50, departureTime: "19:00" },

            // 广州相关连接，构建不同中转情况的后续路径
            { from: "6", to: "7", cost: 10, time: 15, departureTime: "19:00" },
            { from: "6", to: "16", cost: 20, time: 30, departureTime: "20:00" },

            // 株洲相关连接
            { from: "7", to: "8", cost: 25, time: 45, departureTime: "20:00" },

            // 贵阳相关连接
            { from: "8", to: "9", cost: 20, time: 30, departureTime: "21:00" },
            { from: "8", to: "13", cost: 30, time: 50, departureTime: "22:00" },

            // 重庆相关连接
            { from: "9", to: "10", cost: 50, time: 60, departureTime: "22:00" },
            { from: "9", to: "12", cost: 40, time: 50, departureTime: "23:00" },

            // 兰州相关连接
            { from: "10", to: "11", cost: 40, time: 55, departureTime: "23:00" },

            // 其他城市之间的连接，完善全图连接并体现不同策略差异
            { from: "12", to: "13", cost: 50, time: 90, departureTime: "01:00" },
            { from: "13", to: "14", cost: 40, time: 80, departureTime: "02:00" },
            { from: "14", to: "15", cost: 30, time: 70, departureTime: "03:00" },
            { from: "15", to: "16", cost: 25, time: 60, departureTime: "04:00" },
        ]
        localStorage.setItem("EDGE_DATA",JSON.stringify(edges.value))
    } else {
        edges.value = JSON.parse(edge)
    }
}
const tableData = ref([])
getTableData()
function getTableData() { 
    edges.value.forEach((edge) => {
        const src = cityData.value.find((item) => {
            return item.id === edge.from
        }).label
        const dest = cityData.value.find((item) => {
            return item.id === edge.to
        }).label
        const cost = edge.cost
        const departureTime = edge.departureTime
        const time = edge.time
        const arriveTime = calculateArrivalTimeCorrected(departureTime, edge.time)
        tableData.value.push({
            src,dest,cost,departureTime,arriveTime,time
        })
    })
}

function calculateArrivalTimeCorrected  (departureTimeStr, durationMinutes) {

    const [departureHours, departureMinutes] = departureTimeStr.split(':').map(Number);
    
 
    const departureDate = new Date();
    departureDate.setHours(departureHours, departureMinutes, 0, 0); // 设置小时、分钟、秒和毫秒为0
    

    const durationMs = durationMinutes * 60 * 1000;
    departureDate.setTime(departureDate.getTime() + durationMs);
    const arrivalHours = departureDate.getHours().toString().padStart(2, '0');
    const arrivalMinutes = departureDate.getMinutes().toString().padStart(2, '0');
    return `${arrivalHours}:${arrivalMinutes}`;
}

// 点击添加新城市
const handleAddCity = () => {
    if (newCity.value === '') {
        ElMessage.error('请输入新城市')
        return
    }
    const find = cityData.value.find((item) => {
        return item.label === newCity.value
    })
    if (find) {
        ElMessage.warning('该城市已经存在')
        return
    }
    cityData.value.push({ id: Date.now(), label: newCity.value });
    localStorage.setItem('CITY_DATA', JSON.stringify(cityData.value))
    ElMessage.success('添加成功')
}

// 点击添加新路线
const addEdge = () => {
    if (src.value === '' || dest.value === '' || timeRange.value.length === 0) {
        ElMessage.error('请完善内容')
        return
    }
    const find = edges.value.find((item) => {
        return item.from ===  src.value && item.to === dest.value
    })
    if (find) {
        ElMessage.error('该路线已经存在')
        return
    }
    edges.value.push({
        from: src, to: dest,
        cost:price.value,
        time: calculateTimeDifferenceInMinutes(timeRange.value[0], timeRange.value[1]), departureTime: timeRange.value[0]
    })
    localStorage.setItem("EDGE_DATA", JSON.stringify(edges.value))
    getTableData()
    ElMessage.success('添加成功')
}


// 计算时间差
const calculateTimeDifferenceInMinutes = (startTime, endTime) => {
    const start = new Date(`1970-01-01T${startTime}:00Z`); // 使用 UTC 时间并添加 ':00' 秒
    const end = new Date(`1970-01-01T${endTime}:00Z`);
    const differenceInMilliseconds = end - start;

    const differenceInMinutes = differenceInMilliseconds / (1000 * 60);
 

    return differenceInMinutes;
}


// 处理删除
const handleDel = (id) => {
    ElMessageBox.confirm(
        '确认删除?',
        'warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type:'warning'
        }
    ).then(() => {
        cityData.value = cityData.value.filter((item) => {
            return item.id != id
        })
        console.log(cityData.value);
        
        localStorage.setItem('CITY_DATA', JSON.stringify(cityData.value))
        ElMessage.success("删除成功")
   })
    
}
</script>
    
<template>
<div class="admin_container">
    <div class="add_city_bar">
        <el-input placeholder="请输入城市名称" v-model="newCity" style="width: 300px; margin-right: 20px;"></el-input>
        <el-button @click="handleAddCity">添加城市</el-button>
    </div>
     <el-table
      :data="cityData"
       max-height="30vh"
      style="margin-bottom: 20px"
      border
       height="300"
    >
      <el-table-column prop="label" label="城市"  />
       <el-table-column fixed="right" label="操作" min-width="40">
        <template #default="scope">
            <el-button link type="primary" size="small" @click="handleDel(scope.row.id)">
            删除
            </el-button>
        </template>
        </el-table-column>
    </el-table>
    <div class="add_edge_bar">
        <el-select placeholder="选择起始地" style="max-width: 10%; margin-right: 10px;"
        v-model="src">
            <el-option
                v-for="item in cityData"
                :key="item.id"
                :label="item.label"
                :value="item.id"
            />
        </el-select>
        <el-select placeholder="选择目的地" style="max-width: 10%; margin-right: 10px;"
        v-model="dest">
            <el-option
                v-for="item in cityData"
                :key="item.id"
                :label="item.label"
                :value="item.id"
            />
        </el-select>
        <el-input-number :min="1" :max="100000"
        v-model="price">
            <template #prefix>
                <span>￥</span>
            </template>
        </el-input-number>
        <el-time-picker
            is-range
            range-separator="To"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="margin-left: 20px; margin-right: 20px;"
            format="HH:mm"
            value-format="HH:mm"
            v-model="timeRange"
            />
            <el-button @click="addEdge">添加新路线</el-button>
    </div>
    <el-table
      :data="tableData"
      max-height="30vh"
      style="width: 100%; margin-bottom: 20px"
      border
       height="300"
    >
        <el-table-column prop="src" label="出发地"  />
        <el-table-column prop="dest" label="目的地"  />
        <el-table-column prop="cost" label="车票价格"  />
        <el-table-column prop="departureTime" label="发车时间"  />
        <el-table-column prop="arriveTime" label="到达时间"  />
        <el-table-column prop="time" label="耗时"  />
    </el-table>
</div>  
</template>
    
<style>
.add_city_bar ,.add_edge_bar{
    width: 100%;
    margin-bottom: 20px;
}
</style>